/*
 * This file is part of JFlowMap.
 *
 * Copyright 2009 Ilya Boyandin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fons.navigator.views;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Window;

import javax.swing.JComponent;
import javax.swing.JInternalFrame;

import edu.umd.cs.piccolo.PCamera;
import fons.navigator.util.SwingUtils;
import fons.navigator.util.piccolo.PTooltip;

/**
 * @author Ilya Boyandin
 */
public abstract class AbstractCanvasView extends NavigatorAbstractView {

	private VisualCanvas visualCanvas;
	private final PTooltip tooltipBox;

	public AbstractCanvasView(final String name, final ViewConfig config) {
		super(name, config);

		tooltipBox = new PTooltip();
		tooltipBox.setVisible(false);
		tooltipBox.setPickable(false);
		this.visualCanvas = createVisualCanvas();
	}

	public void resetVisualCanvas() {
		if (this.visualCanvas != null) {
			//remove the old canvas and its listeners
			final JInternalFrame frame = visualCanvas.getInternalFrame();
			final Window window = SwingUtils.getWindowFor(frame);
			final Dimension dim = frame.getSize();
			frame.remove(visualCanvas);
			window.removeWindowListener(visualCanvas.getWindowListener());

			//create new canvas
			visualCanvas = createVisualCanvas();

			//use the new canvas
			visualCanvas.setInternalFrame(frame);
			frame.add(visualCanvas, BorderLayout.CENTER);
			window.addWindowListener(visualCanvas.getWindowListener());
			visualCanvas.repaint();
			frame.setPreferredSize(dim);
			frame.pack();
		}
	}

	public PCamera getCamera() {
		return getVisualCanvas().getCamera();
	}

	protected VisualCanvas createVisualCanvas() {
		VisualCanvas visualCanvas = new VisualCanvas(this);
		visualCanvas.getCamera().addChild(tooltipBox);
		return visualCanvas;
	}

	@Override
	public JComponent getControls() {
		return null;
	}

	public VisualCanvas getVisualCanvas() {
		return visualCanvas;
	}

	public void fitInView() {
		visualCanvas.fitChildrenInCameraView();
	}

	public String getData() {
		return null;
	}

	public Frame getParentFrame() {
		Component parent = this.getVisualCanvas();
		while (parent != null) {
			parent = parent.getParent();
			if (parent instanceof Frame) {
				return (Frame) parent;
			}
		}
		return null;
	}
}
